const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const moment = require("moment")
const multerObj = multer({
    dest: "./../src/upluad",
    limits: "5mb"
})
const db = require("./../libs/DBhelper");
let apiRouter = express.Router({
    // strict:true//对路径严格
});
apiRouter.post("/login", function (request, response, next) {
    let parmas=[
        request.body.uname,
        request.body.upwd,
    ]
    let sql = "SELECT `uid`,`uname`,`utel`,`uphoto`,`utype` FROM `userinfo` WHERE ustatus=1 AND uname=? AND upwd=?"
    db.exec(sql, parmas, (err, result) => {
        if(!err && result.length >=1){
            //把当前登录者的信息保存到session
            request.session["userInfo"]=Object.assign({},result);
            response.json({
                msg:"登录成功",
                data:result,
                status:1
            })
        }else{
            response.json({
                msg:"登录失败",
                status:-1,
                err
            })
        }
    })
});

//注册接口
apiRouter.post("/reg",multerObj.any(),function(request,response,next){
    //1，准备后台的参数
    let parmas=[
        request.body.uname,
        request.body.upwd,
        request.body.utel
    ];
    let newpath = request.files[0].path+path.extname(request.files[0].originalname)
    fs.rename(request.files[0].path,newpath,function(err){
        if(!err){
            parmas.push(newpath);//把凭借的新路径，保存到数据库里
            // 准备sql语句
            let sql ="INSERT INTO `userinfo` (`uname`,`upwd`,`utel`,`uphoto`)VALUES(?,?,?,?);";
            db.exec(sql,parmas,function(err,result){
                if(err){
                    response.json({
                        msg:"注册失败",
                        status:-3,
                        err
                    });
                    return;
                }
                if(result.affectedRows >=1){//受影响的行数大于1 表示 插入成功
                    response.json({
                        msg:"注册成功",
                        status:1
                    })
                }else{
                    response.json({
                        msg:"注册失败",
                        status:-1
                    })
                }
            });
        }else{
            response.json({
                msg:"注册异常",
                status:-2,
                err
            })
        }
    })
});
// 注册接口
apiRouter.post("/register",function(request,response,next){
    //1，准备后台的参数
    let parmas=[
        request.body.uname,
        request.body.upwd,
        request.body.utel,
        request.body.uphoto
    ];
    //准备sql语句
    let sql = "INSERT INTO `userinfo` (`uname`,`upwd`,`utel`,`uphoto`)VALUES(?,?,?,?);";
    db.exec(sql,parmas,function(err,result){
        if(err){
            response.json({
                msg:"注册失败",
                status:-3,
                err
            });
            return;
        }
        if(result.affectedRows >=1){
            response.json({
                msg:"注册成功",
                status:1
            })
        }else{
            response.json({
                msg:"注册失败",
                status:-1
            })
        }
    })
})
// 返回很多数据
apiRouter.get("/goodslist",(request,response,next)=>{
    var resJson = JSON.parse(fs.readFileSync("./data/list.json").toString());
    response.json(resJson)
})

//根据id返回一条数据
// post  request.body
// get   request.query
// restfull
apiRouter.get("/goodsById/:pid",(request,response,next)=>{
    let pid=request.params.pid
    var resArr=JSON.parse(fs.readFileSync("./data/list.json").toString());
    //查询之后得到一个新的数
    var reList = resArr.filter((el)=>{
        return el.pid == pid
    })
    if(reList.length>=1){
        response.json({
            msg:"查询成功",
            status:1,
            data:reList[0]
        })
    }else{
        response.json({
            msg:"查询失败",
            status:-1,
            data:null
        })
    }
})

apiRouter.post("/addCart", async (request, response, next) => {
    var parmasQuery = [
        request.body.uid, //购买者
        request.body.pid, //产品编号
        request.body.psize, //规则
        request.body.pname, //产品名称
        request.body.pprice, //产品价格
        request.body.pnum //数量

    ]
console.log(parmasQuery)
    var querySql = "SELECT * FROM cart WHERE u_status=1 AND u_complete=1 AND u_id=? AND p_id=? AND p_size=?";
    var res = await db.execAsync(querySql, parmasQuery);
    // 使用了 await,必须是在 async的函数的内部,并且 await后面的函数是promise
    if (res.length >= 1) {
        //已经购买了 修改数量

        let parmasUpdate = [
            request.body.pnum, //数量
            request.body.uid, //购买者
            request.body.pid, //产品编号
            request.body.psize //规则
        ]


        var updateSql = "UPDATE cart SET p_num=p_num+?,u_total=p_num*p_price  WHERE u_status=1 AND u_complete=1 AND u_id=? AND p_id=? AND p_size=?"

        var res = await db.execAsync(updateSql, parmasUpdate);
        if (res.affectedRows >= 1) {
            response.json({
                msg: "加入购物车成功u",
                status: 1
            })
        } else {
            response.json({
                msg: "加入购物车失败u",
                status: -1
            })
        }
    } else {
        //还没购买,插入新的记录
        var paramsInsert = [
            request.body.pid, //产品编号
            request.body.pname, //产品名称
            request.body.pprice, //产品价格
            request.body.psize, //规则
            request.body.pnum, //数量
            request.body.uid, //购买者
            request.body.pnum * request.body.pprice,
            moment().format("YYYY-MM-DD HH:mm:ss")
        ];
        var insertSQL = "INSERT INTO `cart`(`p_id`,`p_name`,`p_price`,`p_size`,`p_num`,`u_id`,`u_total`,`u_time`)VALUES(?,?,?,?,?,?,?,?)"

        var res = await db.execAsync(insertSQL, paramsInsert);
        if (res.affectedRows >= 1) {
            response.json({
                msg: "加入购物车成功i",
                status: 1
            })
        } else {
            response.json({
                msg: "加入购物车失败i",
                status: -1
            })
        }

    }

})


//get请求
// 参数 uid
apiRouter.get("/shop",async(request,response,next)=>{
    let parmas=[
        request.query.uid
    ]
    let query = "SELECT *FROM `cart` WHERE u_status=1 AND u_complete=1 AND u_id=?";
    var res=await db.execAsync(query,parmas);
    response.json({
        msg:res.length >=1?"查询成功":"查询失败",
        data:res
    });
})

//修改数量
apiRouter.post("/modify",async(request,response,next)=>{
    let paramas=[
        request.body.pnum,
        request.body.cid
    ]
    let sql="UPDATE cart SET p_num=? ,u_total=p_num* p_price  WHERE c_id=? AND  u_status=1 AND u_complete=1";
    var res = await db.execAsync(sql,paramas);
    response.json({
        msg:res.affectedRows >=1?"修改成功":"修改失败",
        status:res.affectedRows >=1?1:-1,
    });
})

// 删除
apiRouter.post("/delete",async(request,response,next)=>{
    let params=[
        request.body.cid
    ]
    let sql="UPDATE cart SET u_status=0 WHERE c_id=? AND  u_status=1 AND u_complete=1";
    var res=await db.execAsync(sql,params)
    response.json({
        msg:res.affectedRows >=1?"删除成功":"删除失败",
        status:res.affectedRows >=1?1:-1
    })
})

// ajax 请求退出
apiRouter.get("/quit",(request,response,next)=>{
    request.session["userInfo"]=null;
    response.clearCookie("loginInfo");
    response.json({
        msg:"退出成功",
        status:1
    })
})

module.exports=apiRouter;
